﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsPipeServer
{
    public partial class FormServer : Form
    {
        private  NamedPipeServerStream m_pipe;
        public FormServer()
        {        
            InitializeComponent();
            m_pipe = new NamedPipeServerStream("Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
            m_pipe.BeginWaitForConnection(ClientConnected, null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(m_pipe.IsConnected)
            {
                var text = string.IsNullOrEmpty(textBox1.Text)?"lala": textBox1.Text;
                m_pipe?.BeginWrite(Encoding.UTF8.GetBytes(text), 0, text.Length, IsSendSucess, null);
            }
        }

        private void IsSendSucess(IAsyncResult ar)
        {
            
        }

        private void ClientConnected(IAsyncResult ar)
        {
            m_pipe.EndWaitForConnection(ar);
            byte[] data = new byte[1000];
            m_pipe.BeginRead(data, 0, data.Length, GotRequest, data);
        }

        private void GotRequest(IAsyncResult ar)
        {
            int bytesRead = m_pipe.EndRead(ar);
            byte[] data = (byte[])ar.AsyncState;
            string message = Encoding.UTF8.GetString(data, 0, bytesRead);
            BeginInvoke(new Action(() => textBox1.Text = message));
            var recvData = new byte[1000];
            m_pipe.BeginRead(recvData, 0, recvData.Length, GotRequest, recvData);
        }
    }
}

